<template>
  <div class="table-with-pagination">
    <!-- 表格 -->
    <el-table
      :data="tableData"
      v-bind="tableProps"
      @selection-change="handleSelectionChange"
    >
      <!-- 动态生成列 -->
      <template v-for="column in columns" :key="column.prop">
        <!-- 普通列 -->
        <el-table-column
          header-align="center"
          align="center"
          v-if="!column.slot"
          v-bind="column"
        ></el-table-column>

        <!-- 插槽列 -->
        <el-table-column
          header-align="center"
          align="center"
          v-else
          v-bind="column"
        >
          <template #default="scope">
            <slot :name="column.slot" v-bind="scope"></slot>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>
  
  <script setup lang="ts">
import { ref, watch } from "vue";

// 定义列的类型
interface TableColumn {
  prop?: string; // 列对应的数据字段
  label?: string; // 列标题
  width?: string | number; // 列宽度
  align?: "left" | "center" | "right"; // 对齐方式
  slot?: string; // 插槽名称（用于自定义列内容）
  [key: string]: any; // 其他 Element Plus 表格列属性
}

// 定义组件 Props
interface Props {
  tableData: any[]; // 表格数据
  columns: TableColumn[]; // 表格列配置
  total: number; // 总条数
  tableProps?: Record<string, any>; // Element Plus 表格的其他属性
}

const props = withDefaults(defineProps<Props>(), {
  tableData: () => [],
  columns: () => [],
  total: 0,
  tableProps: () => ({}),
});

// 定义事件
const emit = defineEmits(["update:page", "update:size", "selection-change"]);

// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10);

// 监听分页变化
watch([currentPage, pageSize], () => {
  emit("update:page", currentPage.value);
  emit("update:size", pageSize.value);
});

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

// 表格选中行变化
const handleSelectionChange = (selection: any[]) => {
  emit("selection-change", selection);
};
</script>
<style scoped>
.table-with-pagination {
  height: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
  /* gap: 16px; */
}

.pagination {
  display: flex;
  width: calc(100% - 2px);
  justify-content: flex-end;
  padding: 5px 0;
  border: 1px solid #dcdfe6;
  border-top: 0;
}
:deep(.el-pagination) {
  margin-top: 0 !important;
}
</style>